package com.ruoyi.project.system.service.impl;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.ResTable;
import com.ruoyi.project.system.mapper.DiagnosisCancelMapper;
import com.ruoyi.project.system.service.IDiagnosisCancelService;

import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 服务层实现（核心业务逻辑）
 */
@Service
public class DiagnosisCancelServiceImpl implements IDiagnosisCancelService {

    // 注入 Mapper 接口（数据库操作）
    @Autowired
    private DiagnosisCancelMapper diagnosisCancelMapper;

    /**
     * 事务注解：确保查询和更新原子性（可选，根据业务需求）
     */
    @Override
    @Transactional
    public boolean updateResolveToTwo(String resId) {
        // 1. 校验 resId 非空
        if (resId == null || resId.trim().isEmpty()) {
            throw new IllegalArgumentException("resId 不能为空");
        }

        // 2. 根据 resId 查询记录（验证是否存在）
        ResTable resTable = diagnosisCancelMapper.selectByResId(resId.trim());
        if (resTable == null) {
            // 无匹配记录，返回 false
            return false;
        }

        // 3. 执行更新：resolve 设为 2
        int affectedRows = diagnosisCancelMapper.updateResolveByResId(
            resId.trim(), 
            2  // 固定更新为 2
        );

        // 4. 返回更新结果（影响行数=1 表示成功）
        return affectedRows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult submitDiagnosis(Map<String, Object> payload) {
        try {
            // 1. 校验必填参数
            String resId = (String) payload.get("ResId");
            if (resId == null || resId.isEmpty()) {
                return AjaxResult.error("ResId不能为空");
            }

            // 2. 向prescription表插入症状和病情说明
            String symptoms = (String) payload.get("symptoms");
            String description = (String) payload.get("description");
            diagnosisCancelMapper.insertPrescription(resId, symptoms, description);

            // 3. 处理per_suggest_list表（康复建议）
            String rehabMode = (String) payload.get("rehabMode");
            Map<String, Object> suggestion = (Map<String, Object>) payload.get("suggestion");
            int mode = "selection".equals(rehabMode) ? 1 : 0;

            if (mode == 1) {
                // 选择模式：保存sports、diet、sleep
                String sports = (String) suggestion.get("sports");
                String diet = (String) suggestion.get("diet");
                String sleep = (String) suggestion.get("sleep");
                diagnosisCancelMapper.insertSelectionSuggest(resId, mode, sports, diet, sleep);
            } else {
                // 手写模式：保存other
                String other = (String) suggestion.get("other");
                diagnosisCancelMapper.insertOtherSuggest(resId, mode, other);
            }

            // 4. 处理药品表（prescription_medicine）
            Map<String, Integer> medicine = (Map<String, Integer>) payload.get("medicine");
            if (medicine != null && !medicine.isEmpty()) {
                Set<String> medIds = medicine.keySet();
                for (String medId : medIds) {
                    int number = medicine.get(medId);
                    diagnosisCancelMapper.insertMedicine(resId, Long.parseLong(medId), number);
                }
            }

            // 5. 更新res_table表的resolve为1（已开方）
            diagnosisCancelMapper.updateResolveByResId(resId, 1);

            return AjaxResult.success("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("提交失败：" + e.getMessage());
        }
    }
}